﻿using Autofac;
using Autofac.Integration.WebApi;
using NHibernate.Tool.hbm2ddl;
using Niusys.Repostories;
using Niusys.WebAPI.Common.Services;
using Odn.Infrastructure;
using Odn.Infrastructure.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Dependencies;

namespace Niusys.WebAPI
{
    public class WebApiModule : IDependencyRegistrar
    {
        public int Order
        {
            get
            {
                return 1;
            }
        }

        public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            //builder.RegisterWebApiFilterProvider(config);

            // Set the dependency resolver to be Autofac.
            //var container = builder.Build();
            config.DependencyResolver = new ControllerDependencyResolver();

            builder.RegisterType<AuthenticationService>().As<IAuthenticationService>().InstancePerRequest();
            builder.RegisterType<UserService>().As<IUserService>().InstancePerRequest();
            builder.RegisterType<ProductService>().As<IProductService>().InstancePerRequest();

            builder.RegisterType<AuthenticationRepository>().As<IAuthenticationRepository>().InstancePerRequest();
            builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerRequest();
            builder.RegisterType<ProductRepository>().As<IProductRepository>().InstancePerRequest();

            builder.RegisterType<SessionManager>().As<ISessionManager>().SingleInstance();
        }
    }

    public class ControllerDependencyResolver : MvcControllerDependencyResolver, IDependencyResolver
    {
        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {
        }
    }

    public class MvcControllerDependencyResolver : System.Web.Mvc.IDependencyResolver
    {
        public object GetService(Type serviceType)
        {
            return EngineContext.Current.ContainerManager.ResolveOptional(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            Type type = typeof(IEnumerable<>).MakeGenericType(serviceType);
            return (IEnumerable<object>)EngineContext.Current.Resolve(type);
        }
    }

    public class DataBaseInit : IStartupTask
    {
        private ISessionManager _sessionManager;
        private IUserService _userService;

        //public DataBaseInit(ISessionManager sessionManager, IUserService userService)
        //{
        //    this._sessionManager = sessionManager;
        //    this._userService = userService;
        //}
        public int Order
        {
            get
            {
                return 1;
            }
        }

        public void Execute()
        {
            _sessionManager = EngineContext.Current.Resolve<ISessionManager>();
            _sessionManager.AddConfiguration("Niusys");


            //var session = _sessionManager.OpenSession();
            var config = _sessionManager.GetConfiguration("Niusys");
            // 创建表结构
            SchemaMetadataUpdater.QuoteTableAndColumns(config);
            new SchemaExport(config).Create(false, true);

            _userService = EngineContext.Current.Resolve<IUserService>();
            _userService.AddUser(new Entities.User() { LoginName = "admin", Password = "admin", IsActive = true, DisplayName = "admin" });
        }
    }
}